package com.tfnswebdesign.common {
  
  /************************************
    ServiceAuth
    [description]
  ************************************/
  
  /*-- imports --*/
  import com.adobe.crypto.HMAC;
  import com.adobe.crypto.SHA256;
  
	public class SessionIDKeyAuth implements iServiceAuth {
    /*-- variables --*/
    private var sessionID:String;
    private var apiKey:String;
    private var apiDomain:String;
    
    public function SessionIDKeyAuth() {
      sessionID = "";
      apiKey = "your api key from drupal services";
      apiDomain = "your api domain from drupal services";
    }
    
    public function register(serverData:*) {
      if (serverData['sessid']) {
        sessionID = serverData['sessid'];
      } else {
        sessionID = "";
      }
      
    }
       
		public function authenticate(serverVariables:Array) {
		  var authVariables = hashKey(serverVariables[0]);
		  authVariables.push(sessionID);
		  return authVariables.concat(serverVariables);
		}
		
		private function hashKey(serviceMethod:String):Array{
      var captureTime:String = (Math.round((new Date().getTime())/1000)).toString();
      var captureRandom:String = randomString(10);
      var hashString:String = captureTime + ";";
      hashString += apiDomain + ";";
      hashString += captureRandom +";";
      hashString += serviceMethod;
      return [HMAC.hash(apiKey,hashString,SHA256),apiDomain,captureTime,captureRandom];
    }
    
    private function randomString(Stringlength:Number):String{
      var allowedChar:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      var allowedArray:Array = allowedChar.split("");
      var randomChars:String = "";
      for (var i:Number = 0; i < Stringlength; i++){
        randomChars += allowedArray[Math.floor(Math.random() * allowedArray.length)];
      }
      return randomChars;
    }
	}	
}

